var pagination = Vue.extend({
    name: 'v-pagination',
    template: ` 
        <nav>
    <ul class="pagination">
      <li :class="{'disabled': current == 1}"><a @click.stop="setCurrent(current - 1)"> « </a></li>
      <li :class="{'disabled': current == 1}"><a @click.stop="setCurrent(1)"> 首页 </a></li>
      <li v-for="p in grouplist" :class="{'active': current == p.val}"><a
                                                                          @click.stop="setCurrent(p.val)"> {{ p.text }} </a>
      </li>
      <li :class="{'disabled': current == page}"><a @click.stop="setCurrent(page)"> 尾页 </a></li>
      <li :class="{'disabled': current == page}"><a @click.stop="setCurrent(current + 1)"> »</a></li>
    </ul>
  </nav>
        `,
    data() {
        return {
            current: this.currentPage
        }
    },
    props: {
        total: { // 数据总条数
            type: Number,
            default: 0
        },
        display: { // 每页显示条数
            type: Number,
            default: 10
        },
        currentPage: { // 当前页码
            type: Number,
            default: 1
        },
        pagegroup: { // 分页条数
            type: Number,
            default: 5,
            coerce: function (v) {
                v = v > 0 ? v : 5;
                return v % 2 === 1 ? v : v + 1;
            }
        }
    },
    computed: {
        page: function () { // 总页数
            return Math.ceil(this.total / this.display);
        },
        grouplist: function () { // 获取分页页码
            this.current = this.currentPage;
            var len = this.page,
                temp = [],
                list = [],
                count = Math.floor(this.pagegroup / 2),
                center = this.current;
            if (len <= this.pagegroup) {
                while (len--) {
                    temp.push({ text: this.page - len, val: this.page - len });
                };
                return temp;
            }
            while (len--) {
                temp.push(this.page - len);
            };
            var idx = temp.indexOf(center);
            (idx < count) && (center = center + count - idx);
            (this.current > this.page - count) && (center = this.page - count);
            temp = temp.splice(center - count - 1, this.pagegroup);
            do {
                var t = temp.shift();
                list.push({
                    text: t,
                    val: t
                });
            } while (temp.length);
            if (this.page > this.pagegroup) {
                (this.current > count + 1) && list.unshift({ text: '...', val: list[0].val - 1 });
                (this.current < this.page - count) && list.push({ text: '...', val: list[list.length - 1].val + 1 });
            }
            return list;
        }
    },
    methods: {
        setCurrent: function (idx) {
            if (this.current != idx && idx > 0 && idx < this.page + 1) {
                this.current = idx;
                this.$emit('pagechange', this.current);
            }
        }
    }
});
Vue.component('v-pagination', pagination);

//阿里上传
var aliUploadModel = Vue.extend({
    mounted: function () {
        // console.log('***-----', this.id)
        // console.log('***-----', this.imgs)
        console.log("===============", this.fileNum, this.upLoadSrc)
        aliUpload({
            uploadDomId: this.id,
            fileNum: this.fileNum,
            progressBar: this.progressBar,
            imgPreview: this.imgPreview,
            upLoadSrc: this.upLoadSrc,
            fileSize: this.fileSize,
            fileFormat: this.fileFormat,
            callBackFunc: function (up, file, fileName) {
                console.log('callBackFunc')
                this.cb(up, file, fileName)
            }.bind(this),
            callBackFuncRemove: function (id) {
                this.rm(id);
            }.bind(this),
            erroeCallBack: function (id) {
                this.err(id);
            }.bind(this),
        })
    },
    data: function () {
        return {}
    },
    template: '<div :id="id" @click.stop="callback">' +
        '<div id="ossfile"></div>' +
        '<div id="container">' +
        '<button id="selectfiles" href="javascript:void(0);" class="btn">选择文件</button>' +
        '</div>' +
        '</div>',
    props: {
        id: {
            type: String,
            default: ''
        },
        fileNum: {
            type: Number,
            default: 3
        },
        progressBar: {
            type: Boolean,
            default: true,
        },
        imgPreview: {
            type: Boolean,
            default: true,
        },
        fileSize: {
            type: String,
            default: '20M',
        },
        fileFormat: {
            type: String,
            // default: "jpg,png"
        },
        upLoadSrc: {
            type: String,
            default: whyConfig.shopProvince + "/image"
        },
        imgs: {
            type: Array,
            default: [],
        },
    },
    methods: {
        callback() {

        },


        cb: function (up, file, fileName) {
            // console.log("cb",file)
            // console.log("fileName",file)

            // console.log(this.imgs)
            // if(this.imgs.length>=3){
            //     return;
            // }
            console.log(2222, file)
            // console.log('fileName', fileName)
            if (file.code < 0) return this.$emit('errmsg', file)
            this.imgs.push(fileName);
            if (this.imgs.length > this.fileNum) {
                this.imgs.shift();
            }
            // console.log("111111111111111", file)
            this.$emit("callback", file, fileName)

        },
        rm: function (id) {
            console.log("这是我打印的", id)
            this.imgs.forEach((item, index) => {
                if (item == id) {
                    this.imgs.splice(index, 1);
                    // console.log(this.imgs)
                }
            })
            // this.$emit('rm', id);
        },
        err: function (id) {

        },
    }
});

// 定义一个名为 ali-upload 的新组件
Vue.component('aliUpload', aliUploadModel)

// 个人展厅 图片预览
var imgPreview = Vue.extend({
    template:
        `<div class="mask" v-if="isVisible" @click="hide">
        <div class="preview-img">
            <i class="iconfont icon-ARROW-left-copy icon-arrow-left" @click.stop="prevImg"></i>
            <i class="iconfont icon-ARROW-right icon-arrow-right" @click.stop="nextImg"></i>
            <img :src="imgList[imgIndex].compositionPicUrl" alt="">
            <div class="preview-content" v-if="isExhibiton">
                <div class="preview-title">作者寄语/创作感想：</div>
                <p class="preview-text">{{imgList[imgIndex].authorMessage}}</p>
            </div>
        </div>
    </div>`,
    data: function () {
        return {
            imgIndex: 0
        }
    },
    props: {
        imgList: {
            type: Array,
            default: () => []
        },
        isVisible: {
            type: Boolean,
            default: false
        },
        // 是否为展厅
        isExhibiton: {
            type: Boolean,
            default: false
        }
    },
    methods: {
        prevImg() {
            const length = this.imgList.length;
            this.imgIndex = this.imgIndex == 0 ? length - 1 : this.imgIndex -= 1
        },
        nextImg() {
            const length = this.imgList.length;
            this.imgIndex = this.imgIndex == length - 1 ? 0 : this.imgIndex += 1
        },
        show(index) {
            this.imgIndex = index;
        },
        hide() {
            this.$emit('close', true);
        }
    }
})
Vue.component('img-preview', imgPreview);

Vue.prototype.oaGetUser = function () {
    return new Promise((resolve, reject) => {
        $.post('/' + whyConfig.shopPath + '/oa/getUser', {}, (res) => {
            if (res.err) return resolve({})
            return resolve(res.data || {});
        });
    })
}
Vue.http.api = function (url, query) {
    query = query || {};
    query._url = url;
    let proxy_url = window.location.origin + '/' + whyConfig.shopPath + '/api';
    return Vue.http.post(proxy_url, query);
}
Vue.http.gateway = function (url, query) {
    query = query || {};
    query._url = url;
    let proxy_url = window.location.origin + '/' + whyConfig.shopPath + '/gateway';
    return Vue.http.post(proxy_url, query);
}
// 河南配送
Vue.http.new = function (url, query) {
    query = query || {};
    query._url = url;
    let proxy_url = window.location.origin + '/' + whyConfig.shopPath + '/new';
    return Vue.http.post(proxy_url, query);
}
// 河南store
Vue.http.store = function (url, query) {
    query = query || {};
    query._url = url;
    let proxy_url = window.location.origin + '/' + whyConfig.shopPath + '/store';
    return Vue.http.post(proxy_url, query);
}
Vue.http.bigData = function (url, query) {
    query = query || {};
    query._url = url;
    let data_url = window.location.origin + '/' + whyConfig.shopPath + '/web/bigData';
    return Vue.http.post(data_url, query);
}
Vue.prototype.getModule = function (id) {
    return new Promise(function (resolve) {
        //资讯模板
        Vue.http.proxy('apiInformation/getInformationModule.do', {
            informationModuleId: id,
            shopPath: creatoo.sp
        }).then(res => {
            let data = res.body;
            if (data.err) {
                console.log('模板出错')
                return
            }
            _data = data.data.data;
            console.log('_data :>> ', _data);
            resolve(JSON.stringify(_data));
        })
    });
}

Vue.prototype.toAd = function (ad) {
    window.open(ad.advertUrl, '_blank');
}


/**
 * 跨域接口封装PC版本
 * @param {*} url 接口地址
 * @param {*} data 接口参数
 * @param {*} isCross 接口是否跨域 默认true
 * @param {*} heas 请求头 
 * @param {*} baseUrl 请求baseUrl
 * @returns 
 */
Vue.prototype.$axios = function (url, data, isCross = true, heas = true, baseUrl = '', isNeedResHeader = false) {
    // whyConfig.apiUrl
    // gateway
    // mdUrl
    // 测试cdn缓存
    const isStore = baseUrl.includes(whyConfig.apiUrl) || baseUrl.includes(whyConfig.mdUrl);
    const isGateway = baseUrl.includes(whyConfig.gateway);
    if (baseUrl.includes(whyConfig.mdUrl)) {
        baseUrl = `${window.location.protocol}//${whyConfig.mdUrl.split('//')[1].split(':')[0]}`
    } else if (baseUrl.includes(whyConfig.apiUrl)) {
        baseUrl = `${window.location.protocol}//${whyConfig.apiUrl.split('//')[1].split(':')[0]}`
    }

    let new_heas = {
        'Content-Type': isStore ? 'application/x-www-form-urlencoded' : 'application/json',
    }

    if (!url.includes('wechat/getWxSign.do')) {
        data = Object.assign({ shopPath: whyConfig.shopPath, shopProvince: whyConfig.shopProvince }, data);
    }
    // i深圳对接
    const userInfo = JSON.parse(sessionStorage.getItem('USERINFO')) || {};
    let headers = {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        'sysPlatform': 'wap',
        'jwtToken': (document.cookie.match(`[;\s+]?jwtToken=([^;]*)`) || []).pop() || userInfo.jwtStr || ''
    };
    headers = heas ? Object.assign(headers, new_heas) : headers;

    // 跨域接口地址
    const urlObj = {
        'gateway': whyConfig.gateway,
        'store': `${window.location.protocol}//${whyConfig.mdUrl.split('//')[1].split(':')[0]}`,
        'china': whyConfig.chinaUrl,
    }

    if (!typeof (axios) == "function") return;
    // 跨域
    if (isCross) {
        return new Promise((resolve, reject) => {
            axios.post(url, isStore ? Qs.stringify(data) : data, {
                baseURL: baseUrl ? baseUrl : whyConfig.gateway,
                method: 'post',
                responseType: isNeedResHeader ? 'arraybuffer' : 'json',
                maxContentLength: 30000,
                headers
            }).then(res => {
                return resolve((isNeedResHeader ? res : res.data) || {});
            })
        })
    } else {
        return new Promise((resolve, reject) => {
            if (baseUrl == urlObj['china']) {
                this.$http.api(url, data).then(res => {
                    if (res.body.err) return resolve({})
                    return resolve(res.body || {});
                })
            } else if (baseUrl == urlObj['store']) {
                this.$http.store(url, data).then((res) => {
                    if (res.body.err) return resolve({})
                    return resolve(res.body || {});
                });
            } else {
                this.$http.gateway(url, data).then((res) => {
                    return resolve(res.body.data || {});
                });
            }
        })
    }
}
